package com.zbl.zblproject.core.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbl.zblproject.core.entity.*;
import com.zbl.zblproject.core.mapper.AdminUserMapper;
import com.zbl.zblproject.core.service.OrderService;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.erp.entity.ErpGoods;
import com.zbl.zblproject.erp.entity.ErpTempOrderItem;
import com.zbl.zblproject.erp.mapper.ErpTempOrderItemMapper;
import com.zbl.zblproject.erp.service.ErpOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/11
 */
@Api(value = "用户订单接口", tags = {"用户订单接口"})
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private ErpOrderService erpOrderService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ErpTempOrderItemMapper erpTempOrderItemMapper;

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);



    @PostMapping("/new-submit-goods")
    @ApiOperation("在购物车中提交订单")
    public Result submitGoodsNew(@ApiParam("购物车ID") @RequestParam("array") String array,
                                 @ApiParam("用户ID") @RequestParam("userId") int userId){
        try {
            AdminUser user = adminUserMapper.selectUserById(userId);
            if (user == null) {
                return ResultUtil.error("没有发现这个用户");
            }
            List<CartItem> cartItems = JSONArray.parseArray(array, CartItem.class);
            //logger.info("json:{}", array);
            orderService.submitOrderNew(cartItems, user);
            return ResultUtil.success("订单生成成功!");
        }catch(RestClientException e){
            e.printStackTrace();
            return ResultUtil.error("远程服务器连接失败!");
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @PostMapping("/submit-goods")
    @ApiOperation("在购物车中提交订单")
    public Result submitGoods(@ApiParam("购物车ID") @RequestParam("ids") String ids,
                              @ApiParam("用户ID") @RequestParam("userId") int userId) {
        //更具订单中供应商的不同产生不同的订单号
        try {
            AdminUser user = adminUserMapper.selectUserById(userId);
            if (user == null) {
                return ResultUtil.error("没有发现这个用户");
            }
            orderService.submitOrders(JSONArray.parseArray(ids, Integer.class), user);
            return ResultUtil.success("订单生成成功!");
        }catch(RestClientException e){
            e.printStackTrace();
            return ResultUtil.error("远程服务器连接失败!");
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/warehouse-delivery/{orderSn}")
    @ApiOperation("通知仓库发货")
    public Result warehouseDelivery(@ApiParam("订单号") @PathVariable String orderSn) {
        if (orderService.warehouseDelivery(orderSn)) {
            return ResultUtil.success("通知成功!");
        }
        return ResultUtil.error("通知失败!");
    }

    @GetMapping("/order-list/{orderSn}")
    @ApiOperation("获取门店订单项")
    public Result orderList(@ApiParam("订单号") @PathVariable String orderSn) {
        return ResultUtil.success("成功", erpTempOrderItemMapper.listByOrderSn(Arrays.asList(orderSn)));
    }


    @PostMapping("/updateContext/{orderSn}")
    @ApiOperation("更新订单备注")
    public Result updateOrderContext(@ApiParam("订单号") @PathVariable String orderSn,
                                     @ApiParam("备注") @RequestParam("context") String context) {
        try {
            if (orderService.updateOrderContext(orderSn, context)) {
                return ResultUtil.success("更新成功!");
            } else {
                return ResultUtil.error("更新失败!");
            }
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @PostMapping("/updateConfirm/{orderSn}")
    @ApiOperation("更新订单确认信息")
    public Result updateOrderComfirm(@ApiParam("订单号") @PathVariable String orderSn,
                                     @ApiParam("状态") @RequestParam("status") int status,
                                     @ApiParam("操作人ID") @RequestParam("userId") int userId) {
        try {
            if (orderService.updateOrderConfirm(orderSn, status, userId)) {
                return ResultUtil.success("更新成功!");
            } else {
                return ResultUtil.error("更新失败!");
            }
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/ended-order/{orderSn}")
    @ApiOperation("订单终结")
    public Result endedOrder(@ApiParam("订单号") @PathVariable String orderSn) {
        if (orderService.orderEnded(orderSn)) {
            return ResultUtil.success("订单终结成功!");
        }
        return ResultUtil.error("订单终结失败!");
    }

    @GetMapping("/factory-order-sn")
    @ApiOperation("获取工厂订单")
    public Result factoryOrderSn(@ApiParam("模式 0:CGDD ") @RequestParam("mode") int mode,
                                 @ApiParam("厂家名称") @RequestParam("name") String name,
                                 @ApiParam("开始时间") @RequestParam("start") String start,
                                 @ApiParam("结束时间") @RequestParam("end") String end,
                                 @ApiParam("订单号") @RequestParam("orderSn") String orderSn) {

        List<FactoryOrder> list = orderService.getSupplierOrderListForOrderSn(mode, start, end, name, orderSn);

        if (list == null) {

            return ResultUtil.error("没有数据");

        }

        return ResultUtil.success("成功", list);

    }

    @GetMapping("/factory-order-sn/{current}/{size}")
    @ApiOperation("获取工厂订单")
    public Result factoryOrderSnByLimit(@ApiParam("模式 0:CGDD ") @RequestParam("mode") int mode,
                                        @ApiParam("厂家名称") @RequestParam("name") String name,
                                        @ApiParam("开始时间") @RequestParam("start") String start,
                                        @ApiParam("结束时间") @RequestParam("end") String end,
                                        @ApiParam("订单号") @RequestParam("orderSn") String orderSn,
                                        @ApiParam("分页") @PathVariable Integer current,
                                        @ApiParam("数量") @PathVariable Integer size) {
        if (current <= 0 || size <= 0) {
            return ResultUtil.error("参数错误");
        }
        return orderService.getSupplierOrderListForOrderSnByLimit(mode, start, end, name, orderSn, current, size);

    }


    @GetMapping("/order-status/{orderSn}/{index}")
    @ApiOperation("获取订单的当前状态")
    public String orderStatus(@ApiParam("订单号") @PathVariable String orderSn,
                              @ApiParam("下标") @PathVariable int index) {
        return index + "," + orderService.orderStatus(orderSn);
    }


    @GetMapping("/factory-order")
    @ApiOperation("获取工厂订单")
    public Result factoryOrder(@ApiParam("模式 0:CGDD 1:非CGDD 2:合并门店订单 ") @RequestParam("mode") int mode,
                               @ApiParam("厂家名称") @RequestParam("name") String name,
                               @ApiParam("开始时间") @RequestParam("start") String start,
                               @ApiParam("结束时间") @RequestParam("end") String end,
                               @ApiParam("订单号") @RequestParam("orderSn") String orderSn) {
        List<FactoryOrder> list = orderService.getSupplierOrder(mode, start, end, name, orderSn);
        if (list == null) {
            return ResultUtil.error("没有数据");
        }
        return ResultUtil.success("成功", list);
    }


    @GetMapping("/factory-order/{factoryName}")
    @ApiOperation("获取工厂订单")
    public Result factoryOrder(@ApiParam("工厂名称") @PathVariable String factoryName) {
        FactoryOrder factoryOrder = orderService.getSupplierOrderByName(factoryName, "", "");
        if (factoryOrder != null) {
            return ResultUtil.success("成功", factoryOrder);
        } else {
            return ResultUtil.error("失败");
        }
    }

    @GetMapping("/order-sn/{factoryName}/{orderSn}")
    @ApiOperation("获取工厂订单")
    public Result orderSn(@ApiParam("工厂名称") @PathVariable String factoryName, @ApiParam("订单号") @PathVariable String orderSn) {
        FactoryOrder factoryOrder = orderService.getSupplierOrderByName(factoryName, orderSn);
        if (factoryOrder != null) {
            return ResultUtil.success("成功", factoryOrder);
        } else {
            return ResultUtil.error("失败");
        }
    }


    @GetMapping("/storelist")
    @ApiOperation("获取门店数据,门店订单引入")
    public Result storeList() {
        return ResultUtil.success("成功!", erpOrderService.getUserOrdersByNotDeliver(0));
    }

    @GetMapping("/confirm-storelist")
    @ApiOperation("获取门店数据,门店订单引入")
    public Result confirmStoreList() {
        return ResultUtil.success("成功!", erpOrderService.getUserOrdersByIsConfirm(0));

    }


    @GetMapping("/erplist")
    @ApiOperation("获取用户可执行ERP订单数据")
    public Result orderList() {
        return ResultUtil.success("成功!", erpOrderService.getOrdersByNotDeliver(0, 0));

    }

    @GetMapping("/owelist/{mode}")
    @ApiOperation("欠缺货订单列表")
    public Result oweList(@ApiParam("欠缺货模式,0:欠货  1:缺货") @PathVariable int mode) {
        return ResultUtil.success("成功", erpOrderService.getOweTtemListByMode(mode));
    }


    @GetMapping("/invoice/{name}")
    @ApiOperation("获取门店的配货单")
    public Result invoice(@ApiParam("门店名称") @PathVariable String name) {
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", name);
        AdminUser user = adminUserMapper.selectOne(wrapper);
        if (user == null || user.getStatus() != 0) {
            return ResultUtil.error("用户不存在或被封禁!");
        }
        return ResultUtil.success("成功", orderService.getInvoiceOrderById(user.getUserId()));
    }

    @GetMapping("/new-invoice/{name}")
    @ApiOperation("获取门店的配货单")
    public Result newInvoice(@ApiParam("门店名称") @PathVariable String name) {
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", name);
        AdminUser user = adminUserMapper.selectOne(wrapper);
        if (user == null || user.getStatus() != 0) {
            return ResultUtil.error("用户不存在或被封禁!");
        }
        return ResultUtil.success("成功", orderService.getInvoiceOrderByIdforWh(user.getUserId()));
    }


    @PostMapping("/add-purchase/{orderNo}")
    @ApiOperation("添加采购单")
    public Result addPurchase(@ApiParam("订单号") @PathVariable String orderNo,
                              @ApiParam("订单商品") @RequestParam("items") String items,
                              @ApiParam("用户ID") @RequestParam("userId") Integer userId,
                              @ApiParam("地址ID") @RequestParam("addressId") Integer addressId,
                              @ApiParam("选中的orderSn") @RequestParam("arrays") String[] arrays) {
        try {
            List<ErpTempOrderItem> list = json2item(items);
            if (list.isEmpty()) {
                throw new RuntimeException("提交的商品数量为空!");
            }
            Order order = orderService.createOrder(orderNo, 0, userId, addressId, 1, 1, 1, 1, list, "");

            orderService.updateOrderOp(order, arrays);
            return ResultUtil.success("成功!", order);
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }


    @PostMapping("/add-store/{mode}/{orderNo}")
    @ApiOperation("添加门店单")
    public Result addStore(@ApiParam("订单号") @PathVariable String orderNo,
                           @ApiParam("订单商品") @RequestParam("items") String items,
                           @ApiParam("用户ID") @RequestParam("userId") Integer userId,
                           @ApiParam("操作者ID") @RequestParam("operator") Integer operatorId,
                           @ApiParam("地址ID") @RequestParam("addressId") Integer addressId,
                           @ApiParam("模式") @PathVariable("mode") Integer mode) {
        try {
            List<ErpTempOrderItem> list = json2item(items);
            if (list.isEmpty()) {
                throw new RuntimeException("提交的商品数量为空!");
            }
            Order order = null;
            if (mode == 1) {
                //提交/创建
                order = orderService.createOrder(orderNo, operatorId, userId, addressId, 1, 0, 0, 0, list, "");
            } else if (mode == 0) {
                //保存订单
                order = orderService.updateOrder(orderNo, operatorId, userId, addressId, 1, 0, 0, 0, list);
            }
            if (order != null) {
                return ResultUtil.success("成功!", order);
            } else {
                return ResultUtil.error("异常的模式");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/copyOrder/{orderSn}")
    @ApiOperation("复制用户订单下面的商品")
    public Result copyOrder(@ApiParam("订单号") @PathVariable String orderSn) {
        List<ErpGoods> list = orderService.getGoodsByOrderSn(orderSn);
        if (list.isEmpty()) {
            return ResultUtil.error("订单项目为空!");
        }
        return ResultUtil.success("成功!", list);
    }


    @GetMapping("/goback/{orderSn}")
    @ApiOperation("该订单的关联订单回滚.")
    public Result goBackOrder(@ApiParam("订单号") @PathVariable String orderSn) {
        return ResultUtil.error("接口未开放!");
    }

    private List<ErpTempOrderItem> json2item(String json) {
        //  logger.info("json信息: {}", json);
        JSONArray array = JSONArray.parseArray(json);
        List<ErpTempOrderItem> list = new ArrayList<>(array.size());
        JSONObject jsonObject = null;
        ErpTempOrderItem orderItem = null;
        for (int i = 0; i < array.size(); i++) {
            jsonObject = array.getJSONObject(i);
            orderItem = new ErpTempOrderItem();
            orderItem.setGoodsId(jsonObject.getInteger("goodsId"));
            orderItem.setGoodsNum(jsonObject.getInteger("goodsNum"));
            orderItem.setGoodsName(jsonObject.getString("goodsName"));
            orderItem.setGoodsUnit(jsonObject.getString("goodsUnit"));
            orderItem.setGoodsDesc(jsonObject.getString("goodsDesc"));
            orderItem.setSpecifications(jsonObject.getString("specifications"));
            orderItem.setBrandName(jsonObject.getString("brandName"));
            orderItem.setOrderItemId(jsonObject.getInteger("orderItemId"));
            list.add(orderItem);
        }
        return list;
    }


}
